/**
 * Created by Administrator on 2017/12/26.
 */
var imgUrl = Feng.ctxPath + "/static/img/loading-upload.gif";
var loading = {
    html: function () { return " <div id='loading-box' class='loading' style='position: absolute; top: 0; bottom: 0px; width: 100%;height:200px; z-index:20000; background: rgba(255, 255, 255,0.6);'><div style='width: 60px; height: 60px; position: absolute; top: 30%; left: 80%;  margin-left: -200px;'><img src="+imgUrl+" width='20' height='20'></div></div>" },
    loading: function () {
        $("body").prepend(this.html());
        this.hide();
    },
    show: function () {
        $("#loading-box").show();
    },
    hide: function () {
        $("#loading-box").hide();
    }
}
loading.loading();
$("#downloadAdd").attr('readonly','readonly');
/**
 * 初始化视频详情对话框
 */
var VedioInfoDlg = {
    VedioInfoData : {},
    validateFields: {
        vedioName: {
            validators: {
                notEmpty: {
                    message: '视频名不能为空'
                }
            }
        },
        filePath: {
            validators: {
                notEmpty: {
                    message: '播放地址不能为空'
                }
            }
        },
        logoPath: {
            validators: {
                notEmpty: {
                    message: 'logo地址不能为空'
                }
            }
        },
        cateList: {
            validators: {
                notEmpty: {
                    message: '所属专辑不能为空'
                }
            }
        },
        ageType: {
            validators: {
                notEmpty: {
                    message: '年龄段不能为空'
                }
            }
        },
        playCount: {
            validators: {
                notEmpty: {
                    message: '播放量不能为空'
                }
            }
        },shareCount: {
            validators: {
                notEmpty: {
                    message: '分享量不能为空'
                }
            }
        },
        rating: {
            validators: {
                notEmpty: {
                    message: '推荐指数不能为空'
                }
            }
        }

    }
};

/**
 * excel上传新增
 */
$("#excel-upload").click(function () {
    loading.show();
    var formData = new FormData();
    formData.append("file", document.getElementById("file").files[0]);
    $.ajax({
        url: Feng.ctxPath + "/vedio/excelAdd",
        type: "post",
        data: formData,
        /**
         *必须false才会自动加上正确的Content-Type
         */
        contentType: false,
        /**
         * 必须false才会避开jQuery对 formdata 的默认处理
         * XMLHttpRequest会对 formdata 进行正确的处理
         */
        processData: false,
        success: function (data) {
            if (data.code == 200) {
                loading.hide();
                alert(data.message);
            } else{
                loading.hide();
                alert(data.message);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            loading.hide();
            alert(textStatus);
        }
    });
});


/**
 * 清除数据
 */
VedioInfoDlg.clearData = function() {
    this.VedioInfoData = {};
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
VedioInfoDlg.set = function(key, val) {
    if(key == 'cateList') {
        if($("#" + key).attr("cateIds") == null || $("#" + key).attr("cateIds") == "undefined") {
            var checkedCatesId = "";
            $("input:checkbox[name='cate_name']:checked").each(function(i) {
                if(i == 0) {
                    checkedCatesId = $(this).val();
                } else {
                    checkedCatesId += "," + $(this).val();
                }

            });
            $("#" + key).attr("cateIds",checkedCatesId);
        }
        this.VedioInfoData[key] = (typeof value == "undefined") ? $("#" + key).attr("cateIds") : value;
    } else if(key =="ageType") {
        if($("#" + key).attr("ageTypeIds") == null || $("#" + key).attr("ageTypeIds") == "undefined") {
            var checkedAgeTypeId = "";
            $("input:checkbox[name='age_name']:checked").each(function(i) {
                if(i == 0) {
                    checkedAgeTypeId = $(this).val();
                } else {
                    checkedAgeTypeId += "," + $(this).val();
                }
            });
            $("#" + key).attr("ageTypeIds",checkedAgeTypeId);
        }
        this.VedioInfoData[key] = (typeof value == "undefined") ? $("#" + key).attr("ageTypeIds") : value;
    }
    else {
        this.VedioInfoData[key] = (typeof value == "undefined") ? $("#" + key).val() : value;
    }
    return this;
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
VedioInfoDlg.get = function(key) {
    return $("#" + key).val();
}

/**
 * 关闭此对话框
 */
VedioInfoDlg.close = function() {
    parent.layer.close(window.parent.Vedio.layerIndex);
};

/**
 * 收集数据
 */
VedioInfoDlg.collectData = function() {
    this.set('id').set('vedioName').set('uploader').set('author').set('fileType')
        .set('filePath').set('logoPath').set('playCount').set('downloadCount').set('shareCount').set('cateList')
        .set('ageType').set('rating').set('recRate');
};

/**
 * 验证数据是否为空
 */
VedioInfoDlg.validate = function () {
    $('#VedioInfoForm').bootstrapValidator('validate');
    return $("#VedioInfoForm").data('bootstrapValidator').isValid();
};

/**
 * 提交添加视频
 */
VedioInfoDlg.addSubmit = function() {

    this.clearData();
    this.collectData();

    if (!this.validate()) {
        return;
    }

    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/vedio/video/add", function(data){
        Feng.success("添加成功!");
        window.parent.Vedio.table.refresh();
        VedioInfoDlg.close();
    },function(data){
        Feng.error("添加失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.VedioInfoData);
    ajax.start();
};

/**
 * 提交修改
 */
VedioInfoDlg.editSubmit = function() {

    this.clearData();
    this.collectData();

    if (!this.validate()) {
        return;
    }

    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/vedio/video/update", function(data){
        Feng.success("修改成功!");
        window.parent.Vedio.table.refresh();
        VedioInfoDlg.close();
    },function(data){
        Feng.error("修改失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.VedioInfoData);
    ajax.start();
};

VedioInfoDlg.batchUpSubmit = function() {
    var ids = "";
    for(var i = 0;i < window.parent.Vedio.seItem.length;i++) {
        if(i < window.parent.Vedio.seItem.length - 1) {
            ids += window.parent.Vedio.seItem[i].id+",";
        } else {
            ids += window.parent.Vedio.seItem[i].id;
        }
    }
    var cateId = "";
    $("input:checkbox[name='batch_cate_name']:checked").each(function (i) {
        if(i == 0) {
            cateId = $(this).val();
        } else {
            cateId += "," + $(this).val();
        }
    });

    var updateData = {};
    updateData['ids'] = ids;
    updateData['cateId'] = cateId;
    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/vedio/video/batchUpCate", function(data){
        Feng.success("修改成功!");
        window.parent.Vedio.table.refresh();
        VedioInfoDlg.close();
    },function(data){
        Feng.error("修改失败!" + data.responseJSON.message + "!");
    });
    console.log(updateData);
    ajax.set(updateData);
    ajax.start();
};

// $(".fileConfig").click(function() {
//     var type = "mp3";
//     //获得信息
//     $.ajax({
//         url: Feng.ctxPath + "/file/getConfig",
//         type: "post",
//         data: {"fileType":type},
//         async:false,
//         success: function (data) {
//             Info.requestUrl = data.requestUrl;
//             Info.authorization = data.authorization;
//             Info.uploadUrl = data.uploadUrl;
//         },
//         error: function (XMLHttpRequest, textStatus, errorThrown) {
//             alert(textStatus);
//         }
//     });
// });
// console.log(Info);
// $(function () {
//     // $("#progressBar").css("width","0%");
//     Feng.initValidator("VedioInfoForm", VedioInfoDlg.validateFields);
//     // 初始化logo上传
//     var iconUp = new $WebFileUpload("logoPath");
//     iconUp.setUploadBarId("progressBar");
//     iconUp.init();
// });
//
// $(function () {
//     // $("#progressBar").css("width","0%");
//     Feng.initValidator("VedioInfoForm", VedioInfoDlg.validateFields);
//     // 初始化音视频上传
//     loading.show();
//     var iconUp = new $WebFileUpload("filePath");
//     iconUp.setUploadBarId("progressBar");
//     iconUp.init();
//     loading.hide();
// });
var auth= {
    uploadUrl:null,
    policy:null,
    authorization:null,
    requestUrl:null,
    signature:null
};

$("#logoPathUploadBtn").click(function () {
    if($("#logoPathUpFile").val() === ""){
        Feng.error('未上传文件！');
        return;
    }
    var fileType = getFileType($("#logoPathUpFile").val());
    var limitType = new Array('gif','jpg','jpeg','bmp','png','svg');
    var isContain = isInArray(limitType,fileType)
    if(!isContain) {
        Feng.error("文件类型错误");
        return;
    }
    getAuth(fileType,'logo');
    upload(auth,'logoPathUpFile','logoPathUploadBtn','logo-parent','logo-bar','logoPath');
});

$("#filePathUploadBtn").click(function () {
    if($("#filePathUpFile").val() === ""){
        Feng.error('未上传文件！');
        return;
    }
    var fileType = getFileType($("#filePathUpFile").val());
    var limitType = new Array('mp4','au','snd','mid','rmi','mp3','aif','aiff','m3u','ra','ram','wav','mp2','mpa','mpe','mpeg','mpg','mpv2','mov','qt','lsf','lsx','asf','asr','asx','avi','movie','flv','3gp','wmv','m3u8','f4v','m4v','mkv','qlv');
    var isContain = isInArray(limitType,fileType)
    if(!isContain) {
        Feng.error("文件类型错误");
        return;
    }
    getAuth(fileType,'video');
    upload(auth,'filePathUpFile','filePathUploadBtn','file-parent','file-bar','filePath');
});

/**
 * 通过栏目查询下面的专辑
 */
var checkedIds = [];
$("#bannerSelecter").change(function () {
    var selectedBannerId = $(this).children('option:selected').val();
    $("#cates input[name='cate_name']:checked").each(function () {
        if(!containId(checkedIds,$(this).val())) {
            checkedIds.push($(this).val());
        }
    });
    $.get(Feng.ctxPath + "/vedio/video/cateInBanner?bannerId=" + selectedBannerId,function (data) {
        $("#cates").empty();
        for (var i = 0; i< data.length;i++) {
            if(containId(checkedIds,data[i].id)) {
                $("#cates").append("<input class='categroys' name='cate_name' value='"+data[i].id+"' cate-name='"+data[i].name+"' type='checkbox' checked='checked'/>"+data[i].name+"&nbsp;&nbsp;&nbsp;&nbsp;")
            } else {
                $("#cates").append("<input class='categroys' name='cate_name' value='"+data[i].id+"' cate-name='"+data[i].name+"' type='checkbox'/>"+data[i].name+"&nbsp;&nbsp;&nbsp;&nbsp;")
            }

        }
    });
});

/**
 * 通过栏目查询下面的专辑
 */
var batchCheckedIds = [];
$("#bannerSelect").change(function () {
    var selectedBannerId = $(this).children('option:selected').val();
    $("#batchUpCateList input[name='batch_cate_name']:checked").each(function () {
        if(!containId(batchCheckedIds,$(this).val())) {
            batchCheckedIds.push($(this).val());
        }
    });
    $.get(Feng.ctxPath + "/vedio/video/cateInBanner?bannerId=" + selectedBannerId,function (data) {
        $("#batchUpCateList").empty();
        for (var i = 0; i< data.length;i++) {
            if(containId(batchCheckedIds,data[i].id)) {
                $("#batchUpCateList").append("<input class='categroys' name='batch_cate_name' value='"+data[i].id+"' cate-name='"+data[i].name+"' type='checkbox' checked='checked'/>"+data[i].name+"&nbsp;&nbsp;&nbsp;&nbsp;")
            } else {
                $("#batchUpCateList").append("<input class='categroys' name='batch_cate_name' value='"+data[i].id+"' cate-name='"+data[i].name+"' type='checkbox'/>"+data[i].name+"&nbsp;&nbsp;&nbsp;&nbsp;")
            }

        }
    });
});

/**
 * 判断是否存在id
 * @param checkIds
 * @param id
 * @returns {boolean}
 */
function containId(checkIds,id) {
    for (var i = 0;i < checkIds.length;i++) {
        if(id == checkIds[i]) {
            return true;
        }
    }
    return false;
}

function isInArray(arr,value){
    for(var i = 0; i < arr.length; i++){
        if(value === arr[i]){
            return true;
        }
    }
    return false;
}

//获取文件名称
function getFileType(path) {
    var pos1 = path.lastIndexOf('/');
    var pos2 = path.lastIndexOf('\\');
    var pos = Math.max(pos1, pos2);
    var name ;
    if (pos < 0) {
        name = path;
    }
    else {
        name = path.substring(pos + 1);
    }
    var index1=name.lastIndexOf(".");
    var index2=name.length;
    var suffix=name.substring(index1+1,index2);
    return suffix;
}

//获取认证信息
function getAuth(fileType,flag) {
    $.ajax({
        url: Feng.ctxPath + "/file/getConfig",
        type: "post",
        data: {"fileType":fileType,"flag":flag},
        async:false,
        success: function (data) {
            auth.uploadUrl = data.uploadUrl;
            auth.policy = data.policy;
            auth.authorization = data.authorization;
            auth.requestUrl = data.requestUrl;
            auth.signature = data.signature;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
}

/**
 * 文件上传
 * @param auth
 * @param id
 * @param submitId
 * @param parent
 * @param bar
 * @param input
 */
function upload(auth,id,submitId,parent,bar,input) {
    $("#"+parent).css('display','block');
    $("#"+submitId).css('pointer-events','none');
    var file = $("#"+id).get(0).files[0];
    var formData = new FormData();
    formData.append('policy',auth.policy);
    formData.append('signature',auth.signature);
    formData.append('file',file);
    $.ajax({
        type: "POST",
        url: auth.uploadUrl,
        data: formData ,
        processData : false,
        contentType : false,
        xhr: function(){
            var xhr = $.ajaxSettings.xhr();
            if(bar == 'logo-bar') {
                if(logoOnprogress && xhr.upload) {
                    xhr.upload.addEventListener("progress" , logoOnprogress, false);
                    return xhr;
                }
            }
            if(bar == 'file-bar') {
                if(fileOnprogress && xhr.upload) {
                    xhr.upload.addEventListener("progress" , fileOnprogress, false);
                    return xhr;
                }
            }
        },
        success:function (data) {
            var jsonData = JSON.parse(data);
            if(jsonData.message=='ok') {
                if(bar == 'file-bar') {
                    $("#"+input).val(auth.requestUrl+jsonData.url);
                    $("#downloadAdd").val(auth.requestUrl+jsonData.url);
                } else {
                    $("#"+input).val(auth.requestUrl+jsonData.url);
                }
            }
            if($("#"+bar).css('width').split("px")[0] == $("#VedioInfoForm").css('width').split("px")[0] -2) {
                setTimeout(function () {
                    $("#"+bar).html("0%");
                    $("#"+bar).css("width", "0%");
                    $("#"+parent).css('display', 'none');
                    $("#"+submitId).css('pointer-events','');
                }, 1000);
            }
        },
        error:function (XMLHttpRequest, textStatus, errorThrown) {
            Feng.error('上传失败，请重试');
            setTimeout(function () {
                $("#"+parent).css('display', 'none');
                $("#"+bar).html("0%");
                $("#"+bar).css("width", "0%");
                $("#"+submitId).css('pointer-events','');
            }, 1000);
        }
    });
}

/**
 * 图片的上传监听
 * @param evbar
 */
function logoOnprogress(evt) {
    var loaded = evt.loaded;                  //已经上传大小情况
    var tot = evt.total;                      //附件总大小
    var per = Math.floor(100 * loaded / tot);      //已经上传的百分比
    $("#logo-bar").html("pic:"+per + "%");
    $("#logo-bar").css("width", per + "%");
}
/**
 * 文件上传的监听
 * @param evt
 */
function fileOnprogress(evt) {
    var loaded = evt.loaded;                  //已经上传大小情况
    var tot = evt.total;                      //附件总大小
    var per = Math.floor(100 * loaded / tot);      //已经上传的百分比
    $("#file-bar").html("video:"+per + "%");
    $("#file-bar").css("width", per + "%");
}

/**
 * 获得专辑并放入input中
 */
VedioInfoDlg.getCates = function () {
    var checkedCatesId = "";
    var checkedCatesName = "";
    $("input:checkbox[name='cate_name']:checked").each(function(i) {
        if(i == 0) {
            checkedCatesId = $(this).val();
            checkedCatesName = $(this).attr("cate-name");
        } else {
            checkedCatesId += "," + $(this).val();
            checkedCatesName += "," + $(this).attr("cate-name");
        }

    });
    $("#cateList").attr("cateIds",checkedCatesId);
    $("#cateList").val(checkedCatesName);
    $("#cateModal").modal('hide');
};

/**
 * 获得专辑并放入input中以便修改
 */
VedioInfoDlg.getCatesUp = function () {
    var checkedCatesId = "";
    var checkedCatesName = "";
    $("input:checkbox[name='cate_name']:checked").each(function(i) {
        if(i == 0) {
            checkedCatesId = $(this).val();
            checkedCatesName = $(this).attr("cate-name");
        } else {
            checkedCatesId += "," + $(this).val();
            checkedCatesName += "," + $(this).attr("cate-name");
        }

    });
    $("#cateList").attr("cateIds",checkedCatesId);
    $("#cateList").val(checkedCatesName);
    $("#cateModalUp").modal('hide');
};

/**
 * 将年龄段信息写入input中
 */
VedioInfoDlg.getAgeTypes = function () {
    var checkedAgeTypeId = "";
    var checkedAgeTypeName = "";
    $("input:checkbox[name='age_name']:checked").each(function(i) {
        if(i == 0) {
            checkedAgeTypeId = $(this).val();
            checkedAgeTypeName = $(this).attr("age-name");
        } else {
            checkedAgeTypeId += "," + $(this).val();
            checkedAgeTypeName += "," + $(this).attr("age-name");
        }

    });
    $("#ageType").attr("ageTypeIds",checkedAgeTypeId);
    $("#ageType").val(checkedAgeTypeName);
    $("#ageModal").modal('hide');
};

/**
 * 将年龄段信息写入input中
 */
VedioInfoDlg.getAgeTypesUp = function () {
    var checkedAgeTypeId = "";
    var checkedAgeTypeName = "";
    $("input:checkbox[name='age_name']:checked").each(function(i) {
        if(i == 0) {
            checkedAgeTypeId = $(this).val();
            checkedAgeTypeName = $(this).attr("age-name");
        } else {
            checkedAgeTypeId += "," + $(this).val();
            checkedAgeTypeName += "," + $(this).attr("age-name");
        }

    });
    $("#ageType").attr("ageTypeIds",checkedAgeTypeId);
    $("#ageType").val(checkedAgeTypeName);
    $("#ageModalUp").modal('hide');
};